package com.etc.dysys.admin.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.etc.dysys.admin.service.ServiceService;
import com.etc.dysys.admin.service.impl.ServiceServiceImpl;
import com.etc.dysys.entity.Service;

/**
 * Servlet implementation class ServiceServlet
 */
@WebServlet("/Service.action")
public class ServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ServiceService ss = new ServiceServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 初始化op
		String op = "query";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}

		if (op.equals("query")) {
			doListServices(request, response);
		}
		if (op.equals("addServiceAjax")) {
			doAddServiceAjax(request, response);
		}
		if (op.equals("deleteService")) {
			doDelService(request, response);
		}
		if (op.equals("updateService")) {
			doUpdService(request, response);
		}
		if (op.equals("updateServiceAjax")) {
			doUpdService02(request, response);
		}
		if (op.equals("stop")) {
			doStopService(request, response);
		}
		if (op.equals("start")) {
			doStartService(request, response);
		}
		if (op.equals("uploadImg")) {
			doAddService(request, response);
		} else if (op.equals("refresh")) {
			doListServices(request, response);
		}
	}

	protected void doAddService(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String sTitle = "", sContent = "", sStatus = "", dId = "", path = "";
		String src = "";
		// 1.创建一个DiskFileItemFactory工厂对象、
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 2.得到一个文件上传处理的临时目录
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// ServletFileUpload核心对象来做文件的上传操作
		ServletFileUpload upload = new ServletFileUpload(factory);

		// 解析request对象
		try {
			List<FileItem> items = upload.parseRequest(request);

			// List的处理 可以使用foreach,也可以使用迭代器
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				// FileItem 一个fileItem理解为一个表单的元素对象
				FileItem item = iter.next();
				// isFormFiled()如果这个item是表单域（表达实际上就是 非文件上传的部分,非文件域）
				if (item.isFormField()) {

					String name = item.getFieldName();
					// 设置编码格式
					String value = item.getString("utf-8");

					// System.out.println("isFormField name" + name + ",value" + value);

					// 判断 匹配
					if (name.equals("sTitle")) {
						sTitle = value;
					}
					if (name.equals("sContent")) {
						sContent = value;
					}
					if (name.equals("sStatus")) {
						sStatus = value;
					} else if (name.equals("dId")) {
						dId = value;
					}

					// System.out.println("判断结果" + sTitle + "," + sContent + "," + sStatus + "," +
					// dId);
				} else {
					// 文件域的处理
					String filedName = item.getFieldName();
					String fileName = item.getName();// 文件名
					String contentType = item.getContentType();
					boolean isInMemory = item.isInMemory();
					long sizeInBytes = item.getSize();// 大小

					// 文件路径
					path = request.getRealPath("/imgs/" + fileName);
					// System.out.println("path:" + path);

					// 构建一个File对象出来
					File uploadedFile = new File(path);
					// 把文件写入指定的路径
					item.write(uploadedFile);
					src = "/imgs/" + fileName;
					System.out.println("上传成功!");
				}

			}

			// 把sStatus dId转换成int数据类型
			int status = Integer.parseInt(sStatus);
			int id = Integer.parseInt(dId);
			// 得到一个Service对象
			Service service = new Service(sTitle, sContent, src, status, id);
			boolean flag = ss.addService02(service);

			doListServices(request, response);

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// doListServices(request, response);
	}

	/**
	 * 变更状态已停用
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doStopService(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-list.jsp传过来的参数
		int sId = Integer.parseInt(request.getParameter("sId"));
		// 获得相应对象
		boolean flag = ss.stopService(sId);
		PrintWriter out = response.getWriter();
		String msg = "已启用";
		if (flag) {
			// msg = "已停用";
			out.print("已停用");
		}
		out.close();
	}

	/**
	 * 变更状态已启用
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doStartService(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-list.jsp传过来的参数
		int sId = Integer.parseInt(request.getParameter("sId"));
		// 获得相应对象
		boolean flag = ss.startService(sId);
		PrintWriter out = response.getWriter();
		String msg = "已停用";
		if (flag) {
			// msg = "已启用";
			out.print("已启用");
		}
		out.close();
	}

	/**
	 * 修改updateajax步骤二
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doUpdService02(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-add.jsp传过来的参数
		int sId = Integer.parseInt(request.getParameter("sId"));
		String sTitle = request.getParameter("sTitle");
		String sContent = request.getParameter("sContent");
		String sUrl = request.getParameter("sUrl");
		int sStatus = Integer.parseInt(request.getParameter("sStatus"));
		int dId = Integer.parseInt(request.getParameter("dId"));

		boolean flag = ss.updateService02(sId, sTitle, sContent, sUrl, sStatus, dId);
		String msg = "修改成功";
		if (!flag) {
			msg = "修改失败";
		}

		PrintWriter out = response.getWriter();

		out.print(msg);
		out.close();
	}

	/**
	 * 修改service步骤一
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doUpdService(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-add.jsp传过来的参数
		int sId = Integer.parseInt(request.getParameter("sId"));
		String sTitle = request.getParameter("sTitle");
		String sContent = request.getParameter("sContent");
		String sUrl = request.getParameter("sUrl");
		int sStatus = Integer.parseInt(request.getParameter("sStatus"));
		int dId = Integer.parseInt(request.getParameter("dId"));

		request.setAttribute("sId", sId);
		request.setAttribute("sTitle", sTitle);
		request.setAttribute("sContent", sContent);
		request.setAttribute("sUrl", sUrl);
		request.setAttribute("sStatus", sStatus);
		request.setAttribute("dId", dId);
		request.getRequestDispatcher("admin/service-update.jsp").forward(request, response);
	}

	/**
	 * 删除service
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doDelService(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-add.jsp传过来的参数
		int sId = Integer.parseInt(request.getParameter("sId"));

		// 调用对象ss的方法
		boolean flag = ss.delServiceById(sId);
		// System.out.println(flag);
		doListServices(request, response);
	}

	/**
	 * ajax添加服务
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doAddServiceAjax(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得从service-add.jsp传过来的参数
		String sTitle = request.getParameter("sTitle");
		String sContent = request.getParameter("sContent");
		String sUrl = request.getParameter("sUrl");
		int sStatus = Integer.parseInt(request.getParameter("sStatus"));
		int dId = Integer.parseInt(request.getParameter("dId"));

		Service service = new Service(sTitle, sContent, sUrl, sStatus, dId);
		// 调用对象ss的方法
		boolean flag = ss.addService02(service);
		// System.out.println(flag);
		PrintWriter out = response.getWriter();
		out.print(flag);
		out.close();
	}

	/**
	 * servece数据的所有列表
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doListServices(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		List<Service> list = ss.findAllServices();
		request.setAttribute("list", list);

		request.getRequestDispatcher("admin/service-list.jsp").forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
